//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <bsp.h>
#include <init.h>
#include <timer.h>

#define PIT_LATCH   ((PIT_ClockRate + krn.uTickRate / 2) / krn.uTickRate)

EXTERN_C DECL_CODEINIT void CDECL InitPIT()
{

    rTINTCSTAT |= (1<<5);

    //  Timer input clock Frequency = PCLK / {prescaler value+1} / {divider value}
    //  {prescaler value} = 0~255
    //  {divider value} = 2, 4, 8, 16
    rTCFG0  = rTCFG0  & ~(0xffffff) | 0x000000;        //prescaler = 0
    rTCFG1  = rTCFG1  & ~(0xffffff) | 0x000003;       //divider value = 8
    BspReloadPIT();

    rTINTCSTAT |= (1<<0);
}

unsigned long LastTimerCount = 0;
EXTERN_C void CDECL BspReloadPIT()
{
//    static uint_t s_uCount = 0;
//    s_uCount++;
//    if (0 == s_uCount % 100) {
//        kprintf("@");
//    }

//    uint_t *sp;
//    ASM("str    %%sp, %0;"
//        :"=m"(sp));
//
//    uint_t *fp;
//    ASM("str    %%fp, %0;"
//        :"=m"(fp));
//
//    kprintf("sp = %x, fp = %x\n", sp, fp);

    //Outl(_OSCR0, 0);
//    kprintf("rTINTCSTAT 0x%x!\n", rTINTCSTAT);
    rTCNTB0 = rTCNTB0 & ~(0xffffffff) | PIT_LATCH;
    rTCMPB0 =  PIT_LATCH - 100;
    rTCON   = rTCON & ~(0x00000f) | 0x2;
    rTCON   = rTCON & ~(0x00000f) | 0x1;
}

EXTERN_C uint_t CDECL BspGetPITTime()
{
    return (rTCNTB0 - rTCNTO0) * PIT_ClockCycle;
}
